package com.example.micro.spider.controller;

import static com.example.micro.spider.controller.IndexController.readFileContent;

import java.awt.Color;
import java.awt.Dimension;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.example.micro.spider.mapper.KkmhManjuMapper;
import com.example.micro.spider.model.KkmhManju;
import com.example.micro.spider.model.KkmhManjuExample;
import com.example.micro.spider.pojo.KkmhData;
import com.example.micro.spider.pojo.KkmhInfo;
import com.example.micro.spider.pojo.KkmhResponse;
import com.kennycason.kumo.CollisionMode;
import com.kennycason.kumo.WordCloud;
import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.bg.CircleBackground;
import com.kennycason.kumo.font.KumoFont;
import com.kennycason.kumo.font.scale.SqrtFontScalar;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.nlp.tokenizers.ChineseWordTokenizer;
import com.kennycason.kumo.palette.ColorPalette;

/**
 * @author liubolun <liubolun@kuaishou.com>
 * Created on 2022-11-12
 */
@RestController
public class KKMHController {

    @Autowired
    private KkmhManjuMapper kkmhManjuMapper;

    @GetMapping("/kkmh")
    public String index() {
        this.load("kkmh");
        return "success";
    }

    public void load(String keyword) {
        String filePath = "/Users/liubolun/Desktop/" + keyword;
        loadOne(new File(filePath), keyword);
    }

    /**
     * 递归获取类文件
     */
    private void loadOne(File fileParent, String keyword) {
        if (fileParent.isDirectory()) {
            File[] childrenFiles = fileParent.listFiles();
            if (childrenFiles == null || childrenFiles.length == 0) {
                return;
            }
            for (File child : childrenFiles) {
                if (child.isDirectory()) {
                    //如果是个文件夹，就继续调用该方法
                    loadOne(child, keyword);
                } else {
                    if (child.isHidden()) {
                        continue;
                    }
                    String path = child.getPath();
                    System.out.println(path);
                    String jsonStr = readFileContent(path);
                    System.out.println(jsonStr);
                    //                    Object parseObj = JSON.parse(jsonStr);
                    KkmhResponse kkmhResponse =
                            JSONObject.parseObject(jsonStr, KkmhResponse.class);
                    this.insertData(kkmhResponse, keyword);
                }
            }
        }
    }

    private void insertData(KkmhResponse kkmhResponse, String keyword) {
        if (kkmhResponse == null) {
            return;
        }
        KkmhData data = kkmhResponse.getData();
        if (data == null) {
            return;
        }
        List<KkmhInfo> items = data.getList();
        if (StringUtils.isEmpty(items)) {
            return;
        }
        for (int i = 0; i < items.size(); i++) {
            KkmhInfo kkmhInfo = items.get(i);
            if (kkmhInfo == null) {
                continue;
            }
            KkmhManju kkmhManju = new KkmhManju();
            kkmhManju.setManjuId(kkmhInfo.getId());
            kkmhManju.setDescription(kkmhInfo.getDescription());
            kkmhManju.setTitle(kkmhInfo.getTitle());
            kkmhManju.setCategoriesJson(JSONObject.toJSONString(kkmhInfo.getCategories()));
            kkmhManjuMapper.insertSelective(kkmhManju);
        }
    }

    @GetMapping("/kkmhWordCloud")
    public String doubanWordCloud() throws IOException {
        List<KkmhManju> kkmhManjuList = kkmhManjuMapper.selectByExample(new KkmhManjuExample());
        kkmhManjuList =
                kkmhManjuList.stream().filter(distinctByKey(KkmhManju::getManjuId)).collect(Collectors.toList());
        kkmhManjuList.forEach(x -> System.out.println(x.getTitle() + " " + x.getCategoriesJson()));
        List<String> categoryList = new ArrayList<>();
        for (KkmhManju kkmhManju : kkmhManjuList) {
            String json = kkmhManju.getCategoriesJson();
            List<String> cate = JSONObject.parseArray(json, String.class);
            cate.forEach(System.out::println);
            categoryList.addAll(cate);
        }
        //        return createWordCloud(categoryList);
        return null;
    }

    @SuppressWarnings("checkstyle:MagicNumber")
    private String createWordCloud(List<String> words) throws IOException {
        FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        frequencyAnalyzer.setWordFrequenciesToReturn(600);
        frequencyAnalyzer.setMinWordLength(2);

        // 引入中文解析器
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());

        final List<WordFrequency> wordFrequencyList = frequencyAnalyzer.load(words);

        // 设置图片分辨率
        Dimension dimension = new Dimension(1269, 1350);
        // 此处的设置采用内置常量即可，生成词云对象
        WordCloud wordCloud = new WordCloud(dimension, CollisionMode.PIXEL_PERFECT);
        java.awt.Font font = new java.awt.Font("STSong-Light", 2, 40);
        wordCloud.setKumoFont(new KumoFont(font));
        wordCloud.setPadding(2);
        wordCloud.setColorPalette(
                new ColorPalette(new Color(0xed1941), new Color(0xf26522), new Color(0x845538), new Color(0x8a5d19),
                        new Color(0x7f7522), new Color(0x5c7a29), new Color(0x1d953f), new Color(0x007d65),
                        new Color(0x65c294)));
        wordCloud.setBackground(new CircleBackground(200));
        wordCloud.setFontScalar(new SqrtFontScalar(10, 40));
        wordCloud.setBackgroundColor(new Color(255, 255, 255));
        //        wordCloud.setBackground(new PixelBoundryBackground(
        //                "/Users/liubolun/IdeaProjects/alibaba-cloud-demo/micro-spider/src/main/resources/static
        //                /0413_1.png"));
        // 生成词云
        wordCloud.build(wordFrequencyList);
        OutputStream output = new ByteArrayOutputStream();
        wordCloud.writeToStream("png", output);
        byte[] outputByte = ((ByteArrayOutputStream) output).toByteArray();
        return org.apache.commons.codec.binary.Base64.encodeBase64String(outputByte);
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
